# 下载华为云上的待办，按照年放到不同文件，每个年份里分未完成待办和已完成待办2部分，未完成在前，已完成在后。两部分待办均按创建时间排序
from pathlib import Path
from time import thread_time, sleep
from huawei_cloud_dariy_deal import *

def query_todo_context(todo_id):
    if not hasattr(query_context, "num"):
        query_context.num = 0
    query_context.num += 1
    url = url_todo_detail
    trace_id = get_trace_id()
    # 要发送的 JSON 数据
    payload = {
        "ctagTaskInfo":"",
        "startCursor":"73472",
        "guid":todo_id,
        "traceId":trace_id
    }

    # 请求头部，带常见鉴权信息
    headers = get_base_header()

    # cookie 信息
    cookies = {
        "userId": userId,
    }

    try:
        # 发送 POST 请求，带超时设置（单位：秒）
        response = requests.post(
            url,
            json=payload,  # 自动转换为 JSON 格式
            headers=headers,
            cookies=cookies,
            timeout=3  # 超时 3s
        )

        # 检查状态码
        response.raise_for_status()

        # 打印返回结果
        print("查询todo详情 状态码: ", response.status_code, "  请求次数: ", query_context.num)
        res_data_str = json.loads(response.text).get("rspInfo").get("data")
        if res_data_str == None:
            print("没有查询到数据，检查cookie、csrftoken 是否过期")
            return None
        res_data = json.loads(res_data_str)
        content = res_data.get("mTaskContent", "")

        todo_info = content.get("mBody", "--")
        todo_detail = content.get("mDescription", "--")
        complete = content.get("mComplete")
        res = {
            "title": todo_info,
            "detail": todo_detail,
            "status": complete,
            "created": content.get("mOrdinaDate", ""),
            "created_readable": timestamp_to_str(content.get("mOrdinaDate", "")),
            "finished_time": timestamp_to_str(content.get("mModifiedTime", "")) if complete == 1 else "--" ,
        }
        return res
    except requests.exceptions.Timeout:
        print("请求超时！")
    except requests.exceptions.RequestException as e:
        print("请求失败:", e)
    except Exception as e:
        print("查询todo详情失败，异常信息: ", e)
    return None


def todo_json_to_str(item):
    todo_title = f"标题: {item.get("title")}"
    detail = f"详情: {item.get("detail")}"
    created_time_read = f"创建时间: {item.get("created_readable")}"
    is_finished = f"完成状态: {"已完成" if item.get("status") == 1 else "未完成"}"
    finished_time = f"完成时间: {item.get("finished_time")}"

    res = "\n".join([todo_title, detail, created_time_read, is_finished, finished_time])
    return res

def download_huawei_todo(output_dir):
    query_res = query_list()
    todo_list = query_res.get("rspInfo", {}).get("taskList", [])
    i = 0
    res_map = {}
    for r in todo_list:
        dairy_data = json.loads(r.get("data", ""))
        guid = dairy_data.get("guid", "")
        item = None
        while item is None:
            item = query_todo_context(guid)
            if item is None:
                print("查询todo详情失败，稍等5s重试...")
                sleep(5)
        read_time_str = item.get("created_readable")
        year = read_time_str.split("/")[0]
        if year not in res_map:
            res_map[year] = {}
        if item["status"] not in res_map[year]:
            res_map[year][item["status"]] = []
        res_map[year][item["status"]].append(item)
        i += 1
        if i >= 5:
            break

    for year in res_map:
        year_data = res_map[year]
        text_arr = []
        iter_keys = list(year_data.keys())
        iter_keys.sort()
        for status in iter_keys:
            arr = year_data[status]
            arr.sort(key=lambda x: x["created"])
            for item in arr:
                text_arr.append(todo_json_to_str(item))
                text_arr.append("\n")

        save_path = os.path.join(output_dir, str(year) + ".txt")
        Path(save_path).parent.mkdir(parents=True, exist_ok=True)
        with open(save_path, "w", encoding="utf-8") as f:
            f.write("\n".join(text_arr))
            print("todo保存完成: ", save_path)



if __name__ == "__main__":
    download_huawei_todo(
        "C:/huawei_download/huawei_todo/",
    )